package com.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.common.constant.HttpStatus;
import com.crm.common.page.TableDataInfo;
import com.crm.common.result.AjaxResult;
import com.crm.common.utils.UserThreadLocal;
import com.crm.domain.Business;
import com.crm.domain.User;
import com.crm.dto.BusinessAddDto;
import com.crm.dto.BusinessListDto;
import com.crm.mapper.BusinessMapper;
import com.crm.mapper.UserMapper;
import com.crm.service.BusinessService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

@Service
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {


    @Autowired
    private UserMapper userMapper;

    @Override
    public TableDataInfo<Business> list(BusinessListDto dto) {
        LambdaQueryWrapper<Business> queryWrapper = buildQueryWrapper(dto);
        // 非公海池数据
        queryWrapper.eq(Business::getIsPool, 0)
                .eq(Business::getDelFlag, 0)
                .orderByDesc(Business::getCreateTime);
        
        Page<Business> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        page = this.page(page, queryWrapper);


        //设置归属人名称
        List<User> userList=userMapper.selectList(new LambdaQueryWrapper<User>()
                .in(User::getUserId,page.getRecords().stream().map(temp->temp.getOwner()).toList()));

        for (Business record : page.getRecords()) {
            if(StringUtils.isEmpty(record.getOwner())){ continue;}



           List<User> tempList=userList.stream().filter(temp->temp.getUserId().toString().equals(record.getOwner())).toList();
           if(!tempList.isEmpty()){
               record.setOwner(tempList.get(0).getUserName());
           }
        }

        
        TableDataInfo<Business> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        return tableDataInfo;
    }

    @Override
    public TableDataInfo<Business> pool(BusinessListDto dto) {
        LambdaQueryWrapper<Business> queryWrapper = buildQueryWrapper(dto);
        // 公海池数据
        queryWrapper.eq(Business::getIsPool, 1)
                .eq(Business::getDelFlag, 0);
        
        Page<Business> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        page = this.page(page, queryWrapper);
        
        TableDataInfo<Business> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setTotal(page.getTotal());
        return tableDataInfo;
    }

    @Override
    public Business getInfo(Long id) {
        return this.getById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean remove(Long[] ids) {
        // 逻辑删除
        List<Business> businesses = this.listByIds(Arrays.asList(ids));
        for (Business business : businesses) {
            business.setDelFlag(1);
        }
        return this.updateBatchById(businesses);
    }
    
    /**
     * 新增商机 (使用DTO)
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addBusiness(BusinessAddDto dto) {
        AjaxResult ajax = new AjaxResult();
        
        // 数据校验
        if (StringUtils.isBlank(dto.getName())) {
            ajax.put("code", 500);
            ajax.put("msg", "商机名称不能为空");
            return ajax;
        }
        
        if (dto.getType() == null) {
            ajax.put("code", 500);
            ajax.put("msg", "商机类型不能为空");
            return ajax;
        }
        
        if (dto.getSourceType() == null) {
            ajax.put("code", 500);
            ajax.put("msg", "商机来源不能为空");
            return ajax;
        }
        
        // 创建业务对象
        Business business = new Business();
        BeanUtils.copyProperties(dto, business);
        
        // 自动生成商机编码
        String code = generateBusinessCode();
        business.setCode(code);
        
        // 设置默认值
        business.setIsPool(0); // 默认不进入公海池
        business.setCreateTime(LocalDateTime.now());
        business.setCreateBy("admin"); // 这里应该从登录用户中获取
        business.setDelFlag(0);
        
        // 设置状态默认值
        if (business.getStatus() == null) {
            business.setStatus("1"); // 0-未处理 1-跟进中 2-已成交 3-已关闭
        }
        
        boolean result = this.save(business);
        
        if (result) {
            ajax.put("code", 200);
            ajax.put("msg", "新增成功");
            ajax.put("data", business);
        } else {
            ajax.put("code", 500);
            ajax.put("msg", "新增失败");
        }
        
        return ajax;
    }
    
    /**
     * 新增商机 (直接使用实体)
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addBusiness(Business business) {
        AjaxResult ajax = new AjaxResult();
        
        // 数据校验
        if (StringUtils.isBlank(business.getName())) {
            ajax.put("code", 500);
            ajax.put("msg", "商机名称不能为空");
            return ajax;
        }
        
        // 自动生成商机编码 BIZ + 年月日 + 4位序号
        String code = generateBusinessCode();
        business.setCode(code);
        
        // 设置默认值
        if (business.getIsPool() == null) {
            business.setIsPool(0); // 默认不进入公海池
        }
        
        business.setCreateTime(LocalDateTime.now());
        business.setCreateBy("admin"); // 这里应该从登录用户中获取
        business.setDelFlag(0);
        
        // 设置状态默认值
        if (business.getStatus() == null) {
            business.setStatus("1"); // 0-未处理 1-跟进中 2-已成交 3-已关闭
        }

        Long userId = UserThreadLocal.getUserId();
        //todo 通过id获取当前用户
        business.setOwner(userId.toString());
        
        boolean result = this.save(business);
        
        if (result) {
            ajax.put("code", 200);
            ajax.put("msg", "新增成功");
            ajax.put("data", business);
        } else {
            ajax.put("code", 500);
            ajax.put("msg", "新增失败");
        }
        
        return ajax;
    }
    
    /**
     * 生成商机编码
     */
    private String generateBusinessCode() {
        // 获取当前日期
        String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        
        // 获取当天最大编码
        String prefixCode = "BIZ" + dateStr;
        LambdaQueryWrapper<Business> queryWrapper = Wrappers.<Business>lambdaQuery()
                .likeRight(Business::getCode, prefixCode)
                .orderByDesc(Business::getCode)
                .last("limit 1");
        
        Business maxBusiness = this.getOne(queryWrapper);
        
        int sequence = 1;
        if (maxBusiness != null && maxBusiness.getCode() != null) {
            String currentCode = maxBusiness.getCode();
            String sequenceStr = currentCode.substring(prefixCode.length());
            try {
                sequence = Integer.parseInt(sequenceStr) + 1;
            } catch (NumberFormatException e) {
                // 转换失败，使用默认值1
            }
        }
        
        // 生成四位序列号
        return prefixCode + String.format("%04d", sequence);
    }
    
    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<Business> buildQueryWrapper(BusinessListDto dto) {
        LambdaQueryWrapper<Business> queryWrapper = Wrappers.lambdaQuery();
        
        queryWrapper.like(StringUtils.isNotBlank(dto.getCode()), Business::getCode, dto.getCode())
                .like(StringUtils.isNotBlank(dto.getName()), Business::getName, dto.getName())
                .like(StringUtils.isNotBlank(dto.getCustomerName()), Business::getCustomerName, dto.getCustomerName())
                .eq(dto.getType() != null, Business::getType, dto.getType())
                .eq(dto.getStatus() != null, Business::getStatus, dto.getStatus())
                .eq(dto.getProgress() != null, Business::getProgress, dto.getProgress())
                .eq(dto.getSourceType() != null, Business::getSourceType, dto.getSourceType());
                
        return queryWrapper;
    }
}
